package org.testis.communicationmodule.services;

import org.testis.communication.data.CommunicationModuleDataObject;
import org.testis.communication.server.AtofTcpServer;
import org.testis.data.TestStepException;
import org.testis.data.TestStepResultType;
import org.testis.logging.AtofLogLevel;
import org.testis.logging.LogSenderService;
import org.testis.services.AtofModuleAction;
import org.testis.services.AtofModuleService;
import org.testis.utils.Networking;

/**
 * A class to define an tcp server action for
 * Communication module
 * @author nurhat
 */
public class TcpServerAction extends AtofModuleAction {

    /**
     * Function  creates a tcp server by using AtofTcpServer.
     * Listen client requests and echo back recieved messages.
     * @param request
     * @return
     */
    @Override
    public boolean operateRequest(AtofModuleService request) {
        CommunicationModuleDataObject dataObj =
                (CommunicationModuleDataObject) request.getDataObj();
        LogSenderService.putMessageOnQueue(
                "TcpServerAction",
                AtofLogLevel.INFO,
                "Starting to execute tcp server action ....with data:" + dataObj.toString() + "....",
                dataObj.getMessageId());
        if (!Networking.isAvailablePort(dataObj.getPort())) {
            throw new TestStepException(
                    TestStepResultType.FAILURE,
                    "Given port to create tcp server is not available right now...");
        }
        AtofTcpServer server = new AtofTcpServer(dataObj.getKeepAliveTime(),
                dataObj.getPort());
        boolean result =
                false;
        String output = null;

        output = server.waitForClientMessage();
        if (output != null) {
            result = true;
        } else {
            output = "N/A";
        }
        AtofLogLevel level = result ? AtofLogLevel.INFO : AtofLogLevel.ERROR;
        LogSenderService.putMessageOnQueue(
                "TcpServerAction",
                level,
                "TcpServerAction executed " + (result ? "" : "un")
                + "successfully..." + (result ? "" : " with error:" + server.getLastError())
                + ".TcpServerAction recieved " + output + " message", dataObj.getMessageId());
        return result;
    }
}
